package tech.veedo.munchkin.services.backend.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import tech.veedo.munchkin.beans.backend.Auditor;
import tech.veedo.munchkin.constants.Type;
import tech.veedo.munchkin.mappers.backend.AuditorMapper;
import tech.veedo.munchkin.services.backend.AuditorService;

import java.util.List;

@Slf4j
@Service
public class AuditorServiceImpl extends ServiceImpl<AuditorMapper, Auditor>  implements AuditorService {

    @Override
    @Transactional
    public boolean saveAuditor(Auditor auditor) {
        Auditor forInsert = new Auditor()
                .setVersion(1L)
                .setNodeID(auditor.getNodeID())
                .setType(Type.PERSON) // 应该获取auditor的类型，但是现在就开放人员类型，这么写也没问题
                .setLv(auditor.getLv())
                .setPsnID(auditor.getPsnID())
                .setPsnName(auditor.getPsnName())
                .setPostCode(auditor.getPostCode())
                .setPostName(auditor.getPostName());

        return save(forInsert);
    }

    @Override
    @Transactional
    public boolean updateAuditor(Auditor auditor) {
        Auditor fromDB = getById(auditor.getId());
        if (ObjectUtils.isEmpty(fromDB)) {
            throw new NullPointerException("要更新的审核人员不存在或已被删除");
        }
        Auditor forUpdate = new Auditor()
                .setLv(auditor.getLv());
        forUpdate.setId(auditor.getId());
        return updateById(forUpdate);
    }

    @Override
    @Transactional
    public boolean deleteAuditor(Long id) {
        Auditor fromDB = getById(id);
        if (ObjectUtils.isEmpty(fromDB)) {
            throw new NullPointerException("要更新的审核人员不存在或已被删除");
        }
//        QueryWrapper<Auditor> wrapper = new QueryWrapper<>();
//        wrapper.eq("node_id", fromDB.getNodeID());
//        if (count(wrapper) == 1) {
//            throw new GlobalException("当前只有一个审核人员，删除后节点没有审核人员");
//        }
        removeById(id);
        // 检查一下删除这个审核人员之后，节点里有没有通过审核的数据，要是换审核人，一定要先增加，后删除
        // code here...
        return true;
    }

    @Override
    public List<Auditor> getAuditorsByNode(Long id) {
        QueryWrapper<Auditor> wrapper = new QueryWrapper<>();
        wrapper.eq("node_id", id)
                .orderByDesc("lv")
                .orderByDesc("create_time");
        return list(wrapper);
    }

}
